import axios from 'axios'
import toast from 'react-hot-toast'

// 创建 axios 实例
const instance = axios.create({
  baseURL: 'http://localhost:3000', // 根据你的后端地址调整
  timeout: 10000,
})

// 是否正在刷新 token
let isRefreshing = false
let requestsQueue = []

// 请求拦截器：统一带上 access_token
instance.interceptors.request.use(
  config => {
    const token = localStorage.getItem('access_token')
    if (token) {
      config.headers.Authorization = token
    }
    return config
  },
  error => Promise.reject(error)
)

// 响应拦截器：处理 401 / token 刷新逻辑
instance.interceptors.response.use(
  res => res.data, // 直接返回 data
  async err => {
    const originalRequest = err.config

    // 如果是 401 并且不是刷新请求本身
    if (err.response?.status === 401 && !originalRequest._retry) {
      originalRequest._retry = true

      // 如果已经在刷新 token，把请求加入队列等待刷新完成
      if (isRefreshing) {
        return new Promise((resolve, reject) => {
          requestsQueue.push({ resolve, reject })
        })
          .then(token => {
            originalRequest.headers.Authorization = token
            return instance(originalRequest)
          })
          .catch(reject => Promise.reject(reject))
      }

      isRefreshing = true
      const refresh_token = localStorage.getItem('refresh_token')

      try {
        const { code, access_token, refresh_token: newRefresh } = 
        await axios.post(
          'http://localhost:3000/user/refresh',
          { refresh_token }
        ).then(r => r.data)

        if (code === '1') {
          // 更新 token
          localStorage.setItem('access_token', access_token)
          localStorage.setItem('refresh_token', newRefresh)

          // 执行队列请求
          requestsQueue.forEach(p => p.resolve(access_token))
          requestsQueue = []
          isRefreshing = false

          // 重试原始请求
          originalRequest.headers.Authorization = access_token
          return instance(originalRequest)
        } else {
          throw new Error('刷新 token 失败')
        }
      } catch (refreshErr) {
        requestsQueue.forEach(p => p.reject(refreshErr))
        requestsQueue = []
        isRefreshing = false
        toast.error('登录失效，请重新登录')
        localStorage.removeItem('access_token')
        localStorage.removeItem('refresh_token')
        localStorage.removeItem('user')
        window.location.href = '/login'
        return Promise.reject(refreshErr)
      }
    }

    // 其他错误直接抛
    return Promise.reject(err)
  }
)

export default instance
